package com.aquarium.ui;

import java.util.Timer;
import java.util.TimerTask;

import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.Button;

import com.aquarium.R;

public class ConnectDialogActivity extends Activity {

	public final static String ACTION_CONNECT_SUCESS = "ACTION_CONNECT_SUCESS";
	public final static String ACTION_CONNECT_FAILED = "ACTION_CONNECT_FAILED";
	public final static String KEY_CONNECT_SECONDS = "KEY_CONNECT_SECONDS";

	private final static int HANDLE_CONNECT_SUCESS = 1;
	private final static int HANDLE_CONNECT_FAILED = 2;

	private Button mOkButton;
	private ConnectDataReceiver mReceiver;
	private int mConnectSeconds;

	private Handler mHandler = new Handler() {
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case HANDLE_CONNECT_SUCESS:
				setResult(RESULT_OK);
				finish();
				break;
			case HANDLE_CONNECT_FAILED:
				setConnectFailedLayout();
				break;
			default:
				break;
			}
		};
	};

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.connect_layout);

		mConnectSeconds = getIntent().getIntExtra(KEY_CONNECT_SECONDS, 5);

		mReceiver = new ConnectDataReceiver();
		IntentFilter filter = new IntentFilter();
		filter.addAction(ACTION_CONNECT_SUCESS);
		filter.addAction(ACTION_CONNECT_FAILED);
		registerReceiver(mReceiver, filter);

		Timer timer = new Timer();
		timer.schedule(new TimerTask() {

			@Override
			public void run() {
				mHandler.sendEmptyMessage(HANDLE_CONNECT_FAILED);
			}
		}, mConnectSeconds * 1000);
	}

	public class ConnectDataReceiver extends BroadcastReceiver {

		@Override
		public void onReceive(Context context, Intent intent) {
			String action = intent.getAction();
			if (ACTION_CONNECT_SUCESS.equals(action)) {
				mHandler.sendEmptyMessage(HANDLE_CONNECT_SUCESS);
			} else if (ACTION_CONNECT_FAILED.equals(action)) {
				mHandler.sendEmptyMessage(HANDLE_CONNECT_FAILED);
			}
		}
	}

	private void setConnectFailedLayout() {
		setContentView(R.layout.connect_fail_layout);
		mOkButton = (Button) findViewById(R.id.send_fail_ok_btn);
		mOkButton.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				setResult(RESULT_CANCELED);
				finish();
			}
		});
	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
		unregisterReceiver(mReceiver);
	}
}
